<?php
/**
 * @Description: 学分培训
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Faculty;

use App\Http\Controllers\Excel\ExcelExport;
use App\Models\Faculty\CreditTraining;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 学分培训 (服务)
 */
class CreditService
{
    /** @var \App\Repositories\Faculty\CreditRepository $creditRepository */
    private $creditRepository;

    public function __construct()
    {
        $this->creditRepository = app('creditRepository');
    }


    /**
     * @Description: 获取教师列表信息数据
     * @Author: kzj
     * @datetime: 2022-11-21
     */
    public function getList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        // dd($request);
        $termId = 0;
        $trainingLevelId = 0;
        $creatorName = ''; //创建人
        $rangeDate = [];
        $filters = [];
        if (isset($request['search']['course_name']) && !empty($request['search']['course_name'])){
            $filters[] = ['course_name', 'like', '%'.$request['search']['course_name'].'%'];
        }
        if (isset($request['search']['course_credit']) && !empty($request['search']['course_credit'])){
            $filters[] = ['course_credit', '=', (int) $request['search']['course_credit']];
        }
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['credit_training_level'] )&& !empty($request['search']['credit_training_level'])){
            $trainingLevelId = $request['search']['credit_training_level'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }

        $user = Auth::user();

        $result = CreditTraining::whereDeleted(0)
            ->when(!empty($filters), function($q) use($filters) {
                $q->where($filters);
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($trainingLevelId > 0, function($q) use($trainingLevelId) {
                $q->whereRaw(" JSON_EXTRACT(`course_level`,'$[0].optionId') = $trainingLevelId");
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('date_time', '>=', $rangeDate[0])->where('date_time', '<=', $rangeDate[1]);
            })
            ->when(!$user->is_checker, function($q) use($user){
                $q->where('user_id', $user->id);
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('user', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->with('term', 'user')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();

        return $result;
    }

    /**
     * @Description: 学分培训单条数据
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function one($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $result = CreditTraining::where('id', $request['id'])->with('user')->first();

        return $result;
    }

    /**
     * @Description: 学分培训数据导出
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function export($request)
    {
        // dd($request);
        $termId = 0;
        $trainingLevelId = 0;
        $creatorName = ''; //创建人
        $rangeDate = [];
        $filters = [];
        if (isset($request['search']['course_name']) && !empty($request['search']['course_name'])){
            $filters[] = ['course_name', 'like', '%'.$request['search']['course_name'].'%'];
        }
        if (isset($request['search']['course_credit']) && !empty($request['search']['course_credit'])){
            $filters[] = ['course_credit', '=', (int) $request['search']['course_credit']];
        }
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['credit_training_level'] )&& !empty($request['search']['credit_training_level'])){
            $trainingLevelId = $request['search']['credit_training_level'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }

        $user = Auth::user();

        $output = CreditTraining::whereDeleted(0)
            ->when(!empty($filters), function($q) use($filters) {
                $q->where($filters);
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('id', $termId);
                });
            })
            ->when($trainingLevelId > 0, function($q) use($trainingLevelId) {
                $q->whereRaw(" JSON_EXTRACT(`course_level`,'$[0].optionId') = $trainingLevelId");
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('date_time', '>=', $rangeDate[0])->where('date_time', '<=', $rangeDate[1]);
            })
            ->when(!$user->is_checker, function($q) use($user){
                $q->where('user_id', $user->id);
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('user', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->with('term', 'user')
            ->get();

            $title = ['学年学期','课程名称','课程级别','获得学分','日期','创建人'];
            $exportData = [];
            foreach($output as $k => $v){
                $item = [
                    'term' => $v->data_version_id ? $v->term->title : '',
                    'name' => $v->course_name,
                    'level' => !empty($v->course_level_set) ? $v['course_level_set'][0]['selectValue'] : '',
                    'course_credit' => $v->course_credit,
                    'date_time' => $v->date_time,
                    'class' => !empty($v->class_item_set) ? $v['class_item_set'][0]['selectValue'] : '',
                    'creator' => !empty($v->user) ? $v->user->nickname : ''
                ];

                $exportData[] = $item;
            }
            array_unshift($exportData, $title);

            $fileName = md5(auth()->user()->id.time()).'.xlsx';
            Excel::store(new ExcelExport($exportData), $fileName, 'excel');

            $result['file_name'] = $fileName;

            return $result;
    }
}
